import { Player, Position, BOARD_SIZE, DIRECTIONS } from '../types/game';

// 智能AI：保持战术水平 + 优化速度
// 开局库 - 更全面的开局指导
const OPENING_BOOK: Position[] = [
  { row: 7, col: 7 }, // 中心点 - 第一步最佳选择
  { row: 6, col: 7 }, { row: 8, col: 7 }, { row: 7, col: 6 }, { row: 7, col: 8 }, // 十字方向
  { row: 6, col: 6 }, { row: 6, col: 8 }, { row: 8, col: 6 }, { row: 8, col: 8 }, // 斜角方向
];

// 位置权重矩阵 - 更精确的评估
const POSITION_WEIGHTS = [
  [0,0,1,1,1,1,1,1,1,1,1,1,1,0,0],
  [0,1,2,2,2,2,2,2,2,2,2,2,2,1,0],
  [1,2,3,3,3,3,3,3,3,3,3,3,3,2,1],
  [1,2,3,4,4,4,4,4,4,4,4,4,3,2,1],
  [1,2,3,4,5,5,5,5,5,5,5,4,3,2,1],
  [1,2,3,4,5,6,6,6,6,6,5,4,3,2,1],
  [1,2,3,4,5,6,7,7,7,6,5,4,3,2,1],
  [1,2,3,4,5,6,7,8,7,6,5,4,3,2,1],
  [1,2,3,4,5,6,7,7,7,6,5,4,3,2,1],
  [1,2,3,4,5,6,6,6,6,6,5,4,3,2,1],
  [1,2,3,4,5,5,5,5,5,5,5,4,3,2,1],
  [1,2,3,4,4,4,4,4,4,4,4,4,3,2,1],
  [1,2,3,3,3,3,3,3,3,3,3,3,3,2,1],
  [0,1,2,2,2,2,2,2,2,2,2,2,2,1,0],
  [0,0,1,1,1,1,1,1,1,1,1,1,1,0,0],
];

// 棋型评估表 - 更精确的评分
const PATTERN_SCORES = {
  FIVE: 1000000,       // 五子连珠 - 立即获胜
  LIVE_FOUR: 100000,   // 活四 - 威胁获胜
  RUSH_FOUR: 50000,    // 冲四 - 强威胁
  LIVE_THREE: 10000,   // 活三 - 中强威胁
  RUSH_THREE: 3000,    // 冲三 - 中等威胁
  LIVE_TWO: 1000,      // 活二 - 弱威胁
  SINGLE: 100          // 单子 - 基础价值
};

// 记忆化缓存 - 减少重复计算
const patternCache = new Map<string, number>();

// 检查五子连珠 - 优化版本
const checkFiveInRow = (board: Player[][], row: number, col: number, player: Player): boolean => {
  for (const { dr, dc } of DIRECTIONS) {
    let count = 1;
    let leftOpen = false, rightOpen = false;
    
    // 正方向检查
    for (let i = 1; i < 5; i++) {
      const newRow = row + dr * i;
      const newCol = col + dc * i;
      if (newRow >= 0 && newRow < BOARD_SIZE && 
          newCol >= 0 && newCol < BOARD_SIZE && 
          board[newRow][newCol] === player) {
        count++;
      } else if (newRow >= 0 && newRow < BOARD_SIZE && 
                 newCol >= 0 && newCol < BOARD_SIZE && 
                 board[newRow][newCol] === null) {
        rightOpen = true;
        break;
      } else {
        break;
      }
    }
    
    // 反方向检查
    for (let i = 1; i < 5; i++) {
      const newRow = row - dr * i;
      const newCol = col - dc * i;
      if (newRow >= 0 && newRow < BOARD_SIZE && 
          newCol >= 0 && newCol < BOARD_SIZE && 
          board[newRow][newCol] === player) {
        count++;
      } else if (newRow >= 0 && newRow < BOARD_SIZE && 
                 newCol >= 0 && newCol < BOARD_SIZE && 
                 board[newRow][newCol] === null) {
        leftOpen = true;
        break;
      } else {
        break;
      }
    }
    
    if (count >= 5) return true;
  }
  return false;
};

// 智能模式检查 - 使用缓存和更精确的评估
const checkSmartPattern = (board: Player[][], row: number, col: number, player: Player): number => {
  if (board[row][col] !== null) return 0;
  
  const cacheKey = `${row}-${col}-${player}-${JSON.stringify(board)}`;
  if (patternCache.has(cacheKey)) {
    return patternCache.get(cacheKey)!;
  }
  
  let totalScore = 0;
  const opponent = player === 'black' ? 'white' : 'black';
  
  // 检查每个方向的棋型
  for (const { dr, dc } of DIRECTIONS) {
    // 构造从-4到+4的线段
    const line: (Player | null)[] = [];
    for (let i = -4; i <= 4; i++) {
      const newRow = row + dr * i;
      const newCol = col + dc * i;
      
      if (newRow >= 0 && newRow < BOARD_SIZE && newCol >= 0 && newCol < BOARD_SIZE) {
        line.push(board[newRow][newCol]);
      } else {
        line.push(null);
      }
    }
    
    const score = evaluateLine(line, player);
    totalScore += score;
  }
  
  // 添加位置权重
  totalScore += POSITION_WEIGHTS[row][col] * 100;
  
  // 缓存结果
  patternCache.set(cacheKey, totalScore);
  return totalScore;
};

// 评估线段的棋型
const evaluateLine = (line: (Player | null)[], player: Player): number => {
  const playerCount = line.filter(cell => cell === player).length;
  const emptyCount = line.filter(cell => cell === null).length;
  const opponentCount = line.filter(cell => cell && cell !== player).length;
  
  if (opponentCount > 0) return 0;
  
  if (playerCount >= 5) return PATTERN_SCORES.FIVE;
  
  // 计算开放程度
  const leftOpen = line[0] === null;
  const rightOpen = line[line.length - 1] === null;
  
  if (playerCount === 4) {
    if (emptyCount === 1 && (leftOpen || rightOpen)) {
      return PATTERN_SCORES.LIVE_FOUR;
    }
    return PATTERN_SCORES.RUSH_FOUR;
  }
  
  if (playerCount === 3) {
    if (emptyCount >= 2) {
      return leftOpen && rightOpen ? PATTERN_SCORES.LIVE_THREE : PATTERN_SCORES.RUSH_THREE;
    }
  }
  
  if (playerCount === 2) {
    if (emptyCount >= 3) {
      return PATTERN_SCORES.LIVE_TWO;
    }
  }
  
  if (playerCount === 1) {
    return PATTERN_SCORES.SINGLE;
  }
  
  return 0;
};

// 智能候选位置生成 - 更精准的搜索策略
const getSmartCandidateMoves = (board: Player[][]): Position[] => {
  const candidates: Position[] = [];
  const visited = new Set<string>();
  
  // 收集所有可能的有意义位置
  for (let row = 0; row < BOARD_SIZE; row++) {
    for (let col = 0; col < BOARD_SIZE; col++) {
      if (board[row][col] === null) {
        // 检查是否与已有棋子相邻（距离<=2）
        let hasNearbyPiece = false;
        for (let dr = -2; dr <= 2; dr++) {
          for (let dc = -2; dc <= 2; dc++) {
            const checkRow = row + dr;
            const checkCol = col + dc;
            if (checkRow >= 0 && checkRow < BOARD_SIZE && 
                checkCol >= 0 && checkCol < BOARD_SIZE && 
                board[checkRow][checkCol] !== null) {
              hasNearbyPiece = true;
              break;
            }
          }
          if (hasNearbyPiece) break;
        }
        
        if (hasNearbyPiece) {
          const key = `${row}-${col}`;
          if (!visited.has(key)) {
            candidates.push({ row, col });
            visited.add(key);
          }
        }
      }
    }
  }
  
  // 如果棋盘为空，返回开局库
  if (candidates.length === 0) {
    return OPENING_BOOK;
  }
  
  // 按位置权重和评估分数排序，优先考虑最有价值的位置
  return candidates.sort((a, b) => {
    const scoreA = POSITION_WEIGHTS[a.row][a.col];
    const scoreB = POSITION_WEIGHTS[b.row][b.col];
    return scoreB - scoreA;
  });
};

// 改进的Alpha-Beta算法 - 更好的剪枝和排序
const smartMinimaxWithPruning = (
  board: Player[][],
  depth: number,
  alpha: number,
  beta: number,
  isMaximizing: boolean,
  player: Player
): { score: number; position?: Position } => {
  const opponent = player === 'black' ? 'white' : 'black';
  
  // 检查游戏结束状态
  for (let row = 0; row < BOARD_SIZE; row++) {
    for (let col = 0; col < BOARD_SIZE; col++) {
      if (board[row][col] === player && checkFiveInRow(board, row, col, player)) {
        return { score: PATTERN_SCORES.FIVE };
      }
      if (board[row][col] === opponent && checkFiveInRow(board, row, col, opponent)) {
        return { score: -PATTERN_SCORES.FIVE };
      }
    }
  }
  
  if (depth === 0) {
    return { score: evaluateBoardSmart(board, player) };
  }
  
  const candidates = getSmartCandidateMoves(board);
  // 限制候选数量但保持足够的选择空间
  const limitedCandidates = candidates.slice(0, Math.min(candidates.length, 25));
  
  // 对候选位置进行启发式排序，优先检查最有前景的位置
  limitedCandidates.sort((a, b) => {
    const scoreA = checkSmartPattern(board, a.row, a.col, player);
    const scoreB = checkSmartPattern(board, b.row, b.col, player);
    return scoreB - scoreA;
  });
  
  if (isMaximizing) {
    let maxScore = -Infinity;
    let bestPosition: Position | undefined;
    
    for (const move of limitedCandidates) {
      const newBoard = [...board];
      newBoard[move.row] = [...newBoard[move.row]];
      newBoard[move.row][move.col] = player;
      
      const result = smartMinimaxWithPruning(newBoard, depth - 1, alpha, beta, false, player);
      
      if (result.score > maxScore) {
        maxScore = result.score;
        bestPosition = move;
      }
      
      alpha = Math.max(alpha, result.score);
      if (beta <= alpha) break;
    }
    
    return { score: maxScore, position: bestPosition };
  } else {
    let minScore = Infinity;
    let bestPosition: Position | undefined;
    
    for (const move of limitedCandidates) {
      const newBoard = [...board];
      newBoard[move.row] = [...newBoard[move.row]];
      newBoard[move.row][move.col] = opponent;
      
      const result = smartMinimaxWithPruning(newBoard, depth - 1, alpha, beta, true, player);
      
      if (result.score < minScore) {
        minScore = result.score;
        bestPosition = move;
      }
      
      beta = Math.min(beta, result.score);
      if (beta <= alpha) break;
    }
    
    return { score: minScore, position: bestPosition };
  }
};

// 智能棋盘评估
const evaluateBoardSmart = (board: Player[][], player: Player): number => {
  let totalScore = 0;
  const opponent = player === 'black' ? 'white' : 'black';
  
  // 评估所有空位的价值
  for (let row = 0; row < BOARD_SIZE; row++) {
    for (let col = 0; col < BOARD_SIZE; col++) {
      if (board[row][col] === null) {
        const myScore = checkSmartPattern(board, row, col, player);
        const opponentScore = checkSmartPattern(board, row, col, opponent);
        totalScore += myScore - opponentScore * 0.8; // 攻击倾向
      }
    }
  }
  
  return totalScore;
};

// 主AI函数 - 智能版本
export const getSmartAIMove = (board: Player[][], aiPlayer: Player): Position => {
  const opponent = aiPlayer === 'black' ? 'white' : 'black';
  
  // 清空缓存，开始新的计算
  patternCache.clear();
  
  // 开局处理
  const emptyCount = board.flat().filter(cell => cell === null).length;
  if (emptyCount >= BOARD_SIZE * BOARD_SIZE - 2) {
    return OPENING_BOOK[0];
  }
  
  // 立即获胜检查
  for (let row = 0; row < BOARD_SIZE; row++) {
    for (let col = 0; col < BOARD_SIZE; col++) {
      if (board[row][col] === null && checkFiveInRow(board, row, col, aiPlayer)) {
        return { row, col };
      }
    }
  }
  
  // 紧急威胁阻挡检查
  for (let row = 0; row < BOARD_SIZE; row++) {
    for (let col = 0; col < BOARD_SIZE; col++) {
      if (board[row][col] === null && checkFiveInRow(board, row, col, opponent)) {
        return { row, col };
      }
    }
  }
  
  // 使用智能Minimax算法，深度为4（保持原有智能水平）
  const result = smartMinimaxWithPruning(board, 4, -Infinity, Infinity, true, aiPlayer);
  
  return result.position || { row: 7, col: 7 };
};